import classNames from 'classnames';
import React, { useEffect, useRef, useState } from 'react';
import { useHistory, useModel } from 'umi';
import request from '@/utils/request';
import { loadScript, uid } from '@/utils';
import styles from './index.less';
import { DownLoadMaterial } from '../../components/Download';
import { message, Popover } from 'antd';
import OrderPayModal, { OriginPayCode, PayCode, PaySuccess } from '../../components/OrderPayModal';
import { allGet } from '@/services/pc';
import wxImg from '@/pages/pc/components/CourseDetail/images/icon-wx.png';
import invoiceBg from '@/pages/pc/video/images/invoice-bg.png';
import VideoPlayerModal from '../../components/VideoPlayer';
import useBuy from '@/hooks/useBuy';
import MaterialModal from '@/pages/pc/components/MaterialModal';
import * as ABC from './abc';
import ReactDOM from 'react-dom';
import AuthModal, { AuthResult } from '@/pages/pc/components/AuthModal';
import { showLogin, handleLogOut } from '@/hooks/login';
import storage from '@/utils/storage';
import { TOKEN, apiUrl } from '@/common/const';

let videoplayCheckStartTimer: any = null;

let catalogueItemIndex = 1;
const transformReward = (data = []) => {
  return [
    {
      type: 'S',
      text:
        data?.[4]?.[1] != 0 || data?.[4]?.[2] != 0
          ? data?.[4]?.[1] != 0
            ? `S:${data?.[4]?.[1]}元RMB`
            : `S:${data?.[4]?.[2]}点CG券`
          : '',
    },
    {
      type: 'A+',
      text:
        data?.[3]?.[1] != 0 || data?.[3]?.[2] != 0
          ? data?.[3]?.[1] != 0
            ? `A+:${data?.[3]?.[1]}元RMB`
            : `A+:${data?.[3]?.[2]}点CG券`
          : '',
    },
    {
      type: 'A',
      text:
        data?.[2]?.[1] != 0 || data?.[2]?.[2] != 0
          ? data?.[2]?.[1] != 0
            ? `A:${data?.[2]?.[1]}元RMB`
            : `A:${data?.[2]?.[2]}点CG券`
          : '',
    },
    {
      type: 'B',
      text:
        data?.[1]?.[1] != 0 || data?.[1]?.[2] != 0
          ? data?.[1]?.[1] != 0
            ? `B:${data?.[1]?.[1]}元RMB`
            : `B:${data?.[1]?.[2]}点CG券`
          : '',
    },
  ];
};

const Wxshare = (props) => {
  const { userInfo } = useModel('user');
  let url = `${location.origin}/center/courses/detail/${props.classId}?sharelid=${props.sharelid}`;
  if (userInfo.uid) {
    url = `${url}&shareuid=${userInfo.uid}`;
  }
  const img = `${apiUrl}?mod=train&do=qrcode&version=pc1.0&url=${encodeURIComponent(url)}`;
  return (
    <div className={styles.wxsharemain}>
      <img loading="lazy" src={img} width="134" height="134" alt="" />
      <div className={styles.title}>
        <img loading="lazy" src={wxImg} alt="" width="19" />
        微信扫码分享
      </div>
    </div>
  );
};

const WorkType = ({ level, currentNum = 0, total = 0 }) => {
  if (total == 0) return null;
  return (
    <div className={styles.workType}>
      <div className={styles.name}> {level} 作业</div>
      <span className={classNames({ [styles.current]: currentNum > 0 })}>{currentNum}</span>/{total}
    </div>
  );
};

const Requirement = ({ text }) => {
  return <div className={styles.main}>{text}</div>;
};

interface CatalogueItemProps {
  /**
   * 1 免费试学
   * 2 正式课（需购买观看）
   * 3 追加课（DLC课时）
   */
  // 0：正式课；-1：试听课：1添加课
  type: any;
  title?: string;
  index?: number;
  onPlay: (vid, permission: boolean) => void;
  lid: any;
  isPay: boolean;

  /**
   *  作业奖励
   */
  workReward?: string;
  // dlc是否解锁
  lock?: boolean;
  /**
   * dlc 解锁条件
   * 1 分享解锁
   * 2 作业解锁
   * 3 支付解锁
   */
  lockType?: 1 | 2 | 3;
  classId;
}
const CatalogueItem: React.FC<CatalogueItemProps> = ({
  type,
  title,
  index,
  onPlay,
  lid,
  isPay = false,
  lock,
  lockType,
  classId,
  ...props
}) => {
  const history = useHistory();
  const anyProps = props as any;
  const paramsLid = (history.location as any)?.query?.lid;
  const { courseDLCBuy, courseBuy } = useBuy();

  // dlc付费解锁
  const handleDLCPay = () => {
    courseDLCBuy({ lid });
  };

  const handleBuyClass = (e) => {
    e.stopPropagation();
    courseBuy({ classid: classId });
  };

  const handlePlay = (id) => {
    let permission = true;
    /**
     * dlc课时，需要单独判断能否播放
     */
    if (type == 1) {
      if (anyProps.unlocked != 1) {
        permission = false;
        message.info('请解锁后观看');
        return;
      }
    }
    // //
    if (type == 0 && !isPay) {
      message.info('请购买后再观看');
      permission = false;
    }

    onPlay(lid, permission);
  };
  // 是否选中该条
  const isActived = paramsLid == lid;

  const renderRight = () => {
    // 免费试学
    if (type == -1) {
      return <div className={styles.sxbutton}>免费试学</div>;
    }
    // 正式课（需购买观看）
    if (type == 0) {
      return (
        <>
          {isPay && (
            <>
              {isActived ? (
                <span className={styles.playing}>正在播放</span>
              ) : (
                <span className={styles.time} />
              )}
            </>
          )}
          {!isPay && (
            <div className={styles.gmbutton} onClick={handleBuyClass}>
              购买后观看
            </div>
          )}
        </>
      );
    }
    // 追加课（DLC课时）
    if (type == 1) {
      // 未解锁
      if (anyProps.unlocked != 1) {
        return <i className={styles.lock} />;
      }
      return null;
    }
    return null;
  };
  const handleShowWrok = () => {
    const busywork = anyProps.busywork;
    VideoPlayerModal.showList({
      data: [{ url: busywork?.video || busywork?.pic }],
    });
  };
  // 上传作业状态文案
  const workText = () => {
    const busywork = anyProps.busywork;
    const hasScore = busywork && busywork.score && parseInt(busywork.score) > 0;
    const reward = transformReward(anyProps.reward);
    return (
      <div className={styles.work}>
        {reward?.some((item) => item?.text) ? (
          <div className={styles.rewardtext}>
            <div className={styles.left}>
              {'完成作业奖励：' +
                reward
                  .filter((item) => item.text)
                  .map((item) => item.text)
                  .join('、')}
            </div>
            <i className={styles.line} />
            <Popover
              getPopupContainer={() => document.getElementById('zhy-menu')!}
              overlayClassName={styles.workRequirement}
              placement="top"
              trigger="hover"
              content={
                <Requirement
                  text={reward
                    .filter((item) => item.text)
                    .map((item) => item.text)
                    .join('、')}
                />
              }
              title={() => null}
            >
              <a className={styles.see}>查看</a>
            </Popover>
          </div>
        ) : (
          '请及时完成作业并上传'
        )}
      </div>
    );
    // 已经评分
    if (hasScore) {
      return <div className={styles.work}>完成作业奖励：{busywork?.reward}</div>;
    }
    // 未上传
    if (!busywork) {
      return <div className={styles.work}>请及时完成作业并上传</div>;
    }
    // 已上传
    return (
      <div className={classNames(styles.work, styles.done)} onClick={handleShowWrok}>
        上传成功，前往查看
        <i className={styles.iconGou} />
      </div>
    );
  };
  // 去上传
  const goUploadWord = () => {
    const busywork = anyProps.busywork;
    if (busywork?.bid) {
      history.push(`/center/upload/work?lid=${lid}&bid=${busywork?.bid}`);
    } else {
      history.push(`/center/upload/work?lid=${lid}`);
    }
  };
  const renderUpload = () => {
    const busywork = anyProps.busywork;
    const hasScore = busywork && busywork.score && parseInt(busywork.score) > 0;
    // 未上传
    if (!busywork) {
      return (
        <div className={styles.button} onClick={goUploadWord}>
          上传
        </div>
      );
    }
    // 已上传未评分
    if (!hasScore && busywork) {
      return (
        <div className={styles.button} onClick={goUploadWord}>
          重新上传
        </div>
      );
    }
    return '';
  };
  // 作业
  const renderExtraWrok = () => {
    // 有作业的
    if (anyProps.allowbusywork == 1) {
      return (
        <div className={classNames(styles.item, styles.extra)}>
          <div className={styles.left}>
            <div className={styles.leftWrapper}>
              <i className={styles.iconEdit} />
              <div style={{ flex: 1 }}>
                {workText()}
                {anyProps.busyworkrequest && (
                  <Popover
                    getPopupContainer={() => document.getElementById('zhy-menu')!}
                    overlayClassName={styles.workRequirement}
                    placement="top"
                    trigger="hover"
                    content={<Requirement text={anyProps.busyworkrequest} />}
                    title={() => null}
                  >
                    <div className={styles.requirement}>
                      作业要求 <i className={styles.icon} />
                    </div>
                  </Popover>
                )}
              </div>
            </div>
          </div>
          {/* <div className={styles.right}>{renderUpload()}</div> */}
        </div>
      );
    }
    return null;
  };
  const renderExtraDLC = () => {
    const { unlock, unlockbusyworkAplus, unlockbusyworkS, unlocks } = anyProps;
    if (unlock === 'share') {
      return (
        <div className={classNames(styles.item, styles.extra)}>
          <div className={styles.left}>
            <div className={styles.lockWrapper}>
              <span className={styles.title}> 解锁条件：</span>
              分享课程解锁该课时
            </div>
          </div>
          <div className={styles.right}>
            <Popover
              overlayClassName={styles.sharepopover}
              placement="left"
              trigger="hover"
              content={<Wxshare classId={classId} sharelid={lid} />}
              title={() => null}
            >
              <div className={styles.button}>分享课程</div>
            </Popover>
          </div>
        </div>
      );
    }
    if (unlock === 'busywork') {
      return (
        <div className={classNames(styles.item, styles.extra)}>
          <div className={styles.left}>
            <div className={styles.lockWrapper}>
              <span className={styles.title}> 解锁条件：</span>
              <WorkType level={'S'} total={unlockbusyworkS} />
              <WorkType level={'A'} total={unlockbusyworkAplus} />
            </div>
          </div>
          {/* <div className={styles.right}>{renderUpload()}</div> */}
        </div>
      );
    }
    if (unlock === 'pay') {
      return (
        <div className={classNames(styles.item, styles.extra)}>
          <div className={styles.left}>
            <div className={styles.lockWrapper}>
              <span className={styles.title}> 解锁条件：</span>
              需要付费 {unlocks}元/节课时
            </div>
          </div>
          <div className={styles.right}>
            <div className={styles.button} onClick={handleDLCPay}>
              支付解锁
            </div>
          </div>
        </div>
      );
    }
    return null;
  };
  const renderExtra = () => {
    // dlc课程
    if (type == 1) {
      // 未解锁显示解锁条件
      if (anyProps.unlocked != 1) {
        return renderExtraDLC();
      }
      // 解锁显示作业
      return renderExtraWrok();
    }

    // 其他课程
    return renderExtraWrok();
  };
  return (
    <>
      <div
        className={classNames(styles.item, styles[`type${type}`], {
          [styles.isActived]: isActived,
          [styles.isPay]: isPay,
        })}
        onClick={() => handlePlay(lid)}
      >
        <div className={styles.left}>
          <span className={styles.index}>{index}.</span>
          <i className={styles.play} />
          <span className={styles.title} title={title}>
            {title}
          </span>
        </div>

        <div className={styles.right}>
          {renderRight()}
          {/* {type == -1 && <div className={styles.sxbutton}>免费试学</div>}
            {type == 0 && <>
                <span className={styles.time}>120:49</span>
                {!isPay && <div className={styles.gmbutton}>购买后观看</div>}
            </>}
            {type == 1 && <i className={styles.lock} />} */}
        </div>
      </div>
      {renderExtra()}
    </>
  );
};

const CollapsibleItem = ({ data, onPlay, isPay, index, hasZhangText = false, classId }) => {
  const [collapsed, setCollapsed] = useState(false);
  if (!data?.children || data?.children?.length <= 0) return null;

  return (
    <div className={classNames(styles.collapsibleItem, { [styles.collapsed]: collapsed })}>
      <div className={styles.header} onClick={() => setCollapsed(!collapsed)}>
        <div className={styles.left}>
          <span className={styles.zj}>{hasZhangText ? `第${index + 1}章` : ''}</span> {data.header}
        </div>
        <i className={styles.arrow} />
      </div>

      <div className={styles.body}>
        {data?.children?.map((item, index) => {
          if (item._index === undefined) {
            item._index = catalogueItemIndex++;
          }
          return (
            <CatalogueItem
              key={item.title}
              onPlay={onPlay}
              classId={classId}
              isPay={isPay}
              index={item._index}
              {...item}
            />
          );
        })}
      </div>
    </div>
  );
};

// 课程目录
const Catalogue = ({ classId, data, isPay, playerRef }) => {
  const history = useHistory();
  const handlePlay = (lid, permission) => {
    if (permission) {
      const top = document.getElementById('zhy-menu')?.scrollTop || 0;
      clearTimeout(videoplayCheckStartTimer);
      console.log(videoplayCheckStartTimer);
      console.log('点击播放 ->> 清除视频检查定时器', Date.now());
      history.replace(`/center/video/player/${classId}?lid=${lid}&top=${top}`);
      //location.href = `/center/video/player/${classId}?lid=${lid}&top=${top}`;
      playerRef.current.play(lid);
      // playerRef.current.changeVid({
      //   vid: lid
      // });
    }
  };
  catalogueItemIndex = 1;
  return (
    <div className={styles.catalogue}>
      {data.map((item, index) => {
        return (
          <CollapsibleItem
            key={item.header}
            data={item}
            classId={classId}
            onPlay={handlePlay}
            hasZhangText={data.length > 1}
            isPay={isPay}
            index={index}
          />
        );
      })}
    </div>
  );
};

const useShowPayCode = () => {
  const container = useRef<any>();
  const id = useRef<any>();
  const timer = useRef<any>(null);
  const check = useRef<any>();
  const onClose = useRef(() => {});

  const handleClose = () => {
    if (timer.current) {
      clearTimeout(timer.current);
    }
    ReactDOM.unmountComponentAtNode(container.current);
    if (document.getElementById(id.current)) {
      document.body.removeChild(container.current);
    }
  };
  const checkFun = async () => {
    clearTimeout(timer.current);
    timer.current = null;
    const response: any = await request.get(check.current);
    if (response?.data?.check == 0) {
      timer.current = setTimeout(checkFun, 2000);
    } else {
      onClose.current?.();
      handleClose();
    }
  };
  const show = (title, qrcode, _check, _onClose) => {
    onClose.current = _onClose;
    check.current = _check;
    container.current = document.createElement('div');
    id.current = uid() + '' + Date.now();
    container.current.setAttribute('id', id.current);
    document.body.appendChild(container.current);
    ReactDOM.render(
      <OriginPayCode
        data={{ qrCode: qrcode }}
        title={title}
        type="wxcode"
        container={container.current}
        visible={true}
        destroyOnClose
        onClose={handleClose}
        onLoad={() => {
          timer.current = setTimeout(() => {
            checkFun();
          }, 3000);
        }}
      />,
      container.current,
    );
  };

  useEffect(() => {
    if (check.current) {
      timer.current = setTimeout(checkFun, 2000);
    }
  }, [check.current]);

  return {
    show,
    close: () => handleClose(true),
  };
};

const Left = ({ playerRef, isPay, classDetail }) => {
  const player = useRef<any>(null);
  const history = useHistory();
  const showCode = useShowPayCode();
  const paramsVid = (history.location as any)?.query?.vid;
  const [showPopup, setShowPopup] = useState(false);
  // useEffect(() => {
  //   if (!window.polyvPlayer) {
  //     loadScript('https://player.polyv.net/script/player.js').then(() => {
  //       loadPlayer();
  //     });
  //   }
  // }, []);

  const loadPlayer = () => {
    // player.current = window.polyvPlayer({
    //   wrap: '#zhy-cjjoy-video-player',
    //   width: '100%',
    //   height: '100%',
    //   // autoplay: true,
    //   vid: 'ace08f75ead8a5fbf2dba6afdb5878f5_a',
    //   playsafe: '4e9aca1c-8367-4eb4-82fa-83b37f864355-18',
    //   code: 'NzkxMXwzMjAyOTNjNXwxNjgzMjk3MjkxfDV8MA%3D%3D'
    // });
  };

  const [videoSrc, setVideoSrc] = useState('');
  const [downurl, setDownurl] = useState('');
  const [iframeUrl, setIframeUrl] = useState('');
  const lidRef = useRef('');
  const play = async (lid) => {
    lidRef.current = lid;
    setDownurl('');
    if (player.current) {
      if (player.current?.destroy) {
        player.current?.destroy?.();
      }
    }
    console.log('点击播放->>>>', Date.now());
    setIframeUrl(
      `/api/app.php?mod=lesson&do=detail&lid=${lid}&version=pc1.0&token=${encodeURIComponent(
        storage.get(TOKEN).value,
      )}&t=${Date.now()}`,
    );
  };
  playerRef.current = {
    play,
  };

  const afterIframeLoadPlay = async (lid, response) => {
    // console.log(response, 'afterIframeLoadPlay');
    let nologinModal: any = null;
    // const response = await allGet({
    //   params: { mod: 'lesson', do: 'detail', lid, version: 'pc1.0' },
    //   headers: { 'New-User-Agent': newUserAgent },
    // });
    if (response.success) {
      // const key = response.data?.baijiayun.key;
      // console.log('--->', response)
      if (response.data.playererror !== null) {
        const { go, msg, check, qrcode } = response.data.playererror;
        if (go !== 'bindweixin' && go !== 'weixinscan') {
          message.error(msg);
        }
        switch (go) {
          case 'bindweixin':
          case 'weixinscan': {
            // ! 后端接口返回结构 qrcode 如果为url格式则可以直接使用，如果为接口地址需要拼接前缀/api/
            showCode.show(msg, qrcode, '/api/' + check, () => {
              window.location.reload();
              // play(lid);
            });
            break;
          }
          case 'verify': {
            // todo "您的身份认证没审核通过，请先身份认证再进行此操作,点击认证，如有疑问，请咨询在线客服"
            AuthModal.show({
              onSuccess: async (values, type) => {
                AuthResult.show({
                  onClick: () => {},
                });
              },
            });
            break;
          }
          case 'player_error': {
            // 下载播放器
            setDownurl(response.data.playererror.downurl);
            break;
          }
          case 'login': {
            // todo 登录
            if (nologinModal) return;
            nologinModal = showLogin({
              title: '请先登录',
              okText: '立即登录',
              cancelText: '取消',
              onCancel: () => {
                nologinModal = null;
              },
            });
            break;
          }
        }
        return;
      }
      if (response.data?.videoisurl != 1) {
        switch (response.data?.platform) {
          // *百家云视频
          case 'baijiayun': {
            const key = response.data?.baijiayun.marquee?.substr(-16);
            const token = response.data?.baijiayun?.token;
            const timestamp = response.data?.timestamp;
            const decrypt = ABC.AES.decrypt;
            const newToken = decrypt(token, key, timestamp + '');
            // console.log(response.data?.baijiayun);
            // console.log('token1-->', token);
            // console.log('key-->', key);
            // console.log('timestamp-->', timestamp);
            // console.log('解密的出来的token->', newToken);

            setVideoSrc('');
            const dom = document.getElementById('zhy-cjjoy-video-player');
            if (dom) {
              dom.innerHTML = '';
            }
            setTimeout(() => {
              const config = {
                container: document.getElementById('zhy-cjjoy-video-player'), // 设置播放器初始化的父容器
                memory: true, // 是否开启记忆播放
                enableLogo: false,
                preload: 'meta', // 预加载，推荐设置 meta
                quality: response.data.baijiayun.df,
                qualityList: [response.data.baijiayun.df],
                vid: response.data.baijiayun.vid, // 百家云后台视频id
                token: newToken, // 视频id 对应token
                plugins: {
                  // 跑马灯
                  marquee: {
                    ...(response.data.baijiayun?.marquees || {}),
                    value: response.data.baijiayun?.marquee,
                  },
                },
              };
              console.log(response.data.baijiayun.df);
              console.log('BPlayer 初始化');
              player.current = new window.BPlayer(config);
              // 检查是否开发票
              invoiceCheck(response.data.classid);
            }, 100);
            break;
          }
          // *保利威视频
          case 'polyv': {
            const video = response.data?.video;
            const playSafe1 = response.data?.polyv?.playSafe1;
            const timestamp = response.data?.timestamp;
            const code = response.data?.polyv?.code;
            const decrypt = ABC.AES.decrypt;
            const playSafe = decrypt(playSafe1, video?.substr(0, 16), timestamp + '');
            const config = {
              wrap: '#zhy-cjjoy-video-player',
              width: '100%',
              height: '100%',
              // autoplay: true,
              vid: video,
              playsafe: playSafe,
              code: code,
            };
            setVideoSrc('');
            setTimeout(() => {
              const dom = document.getElementById('zhy-cjjoy-video-player');
              if (dom) {
                dom.innerHTML = '';
              }
              player.current = window.polyvPlayer(config);
              // 检查是否开发票
              invoiceCheck(response.data.classid);
            }, 500);
          }
        }
      } else {
        setVideoSrc(response.data?.video);
        player.current = {};
      }
      videoplayCheck(response.data);
    }
  };

  const videoplayCheck = (data) => {
    clearTimeout(videoplayCheckStartTimer);
    const fn = async () => {
      console.log(`执行检查视频请求${data.lid}的一次轮询->>>`, Date.now());
      const response = await allGet({
        params: {
          platform: window ? window.navigator.userAgent : '',
          mod: 'course',
          do: 'videoupdate',
          classid: data.classid,
          lid: data.lid,
          time: data.timestamp,
          version: 'pc1.0',
        },
        skipErrorHandler: true,
      });
      if (!response.success) {
        console.log('轮询接口返回不是response.success退出了');
        handleLogOut();
        clearTimeout(videoplayCheckStartTimer);
        return;
      }
      videoplayCheckStartTimer = setTimeout(fn, data.refreshtime);
    };
    videoplayCheckStartTimer = setTimeout(fn, data.refreshtime);
  };
  const invoiceCheck = async (classId) => {
    const params: any = {
      mod: 'invoice',
      do: 'detail',
      classid: classId,
      version: 'pc1.0',
    };
    const res = await allGet({ params });
    if (res.code == 1) {
      setShowPopup(true);
    }
  };

  useEffect(() => {
    if (showPopup) {
      // 创建弹出框容器
      const popupContainer = document.createElement('div');
      popupContainer.id = 'video-player-popup';
      popupContainer.className = styles.invoicePopup;
      document.body.appendChild(popupContainer);

      // 渲染弹出框内容
      ReactDOM.render(
        <div>
          <div className={styles.invoiceMask}></div>
          <div className={styles.invoice}>
            <div className={styles.invoiceHeader}>
              <img src={invoiceBg} />
            </div>
            <div className={styles.invoiceBody}>
              宝子们好呀～小提示：按国家政策，网上买的东西得开规范发票，能妥妥保障咱们的消费权益，请先处理下开发票的事儿呀～
            </div>
            <div className={styles.invoiceFooter}>
              <a className={styles.one} onClick={() => history.push('/learning?index=4')}>
                前往开具发票
              </a>
              <a onClick={() => history.push('/learning?index=1')}>学习中心</a>
            </div>
          </div>
        </div>,
        popupContainer,
      );

      // 清理函数
      return () => {
        ReactDOM.unmountComponentAtNode(popupContainer);
        if (document.body.contains(popupContainer)) {
          document.body.removeChild(popupContainer);
        }
      };
    }
  }, [showPopup]);

  // const [x, setx] = useState('');
  const useragentIframe = useRef<HTMLIFrameElement>();
  const iframeLoad = () => {
    const iframeDcoument =
      useragentIframe.current?.contentDocument || useragentIframe.current?.contentWindow?.document;
    const string = iframeDcoument?.querySelector('pre')?.innerText || '';
    const data = JSON.parse(string);
    afterIframeLoadPlay(lidRef.current, data);
    // setx(string);
    // alert(data.useragent);
    //const useragentDom = iframeDcoument?.getElementById('useragent');
    // console.log(useragentDom?.innerHTML, 444444);
    // afterIframeLoadPlay(lidRef.current, useragentDom?.innerHTML);
  };

  const goTeacherDetail = (id) => {
    window.open(`/teachers/detail/${id}`);
  };

  useEffect(() => {
    return () => {
      if (player.current) {
        player.current.destroy();
      }
    };
  }, []);
  return (
    <div className={styles.leftVideoWrapper} id="leftVideoWrapper">
      {/* <div style={{ wordBreak: 'break-all' }}>{x}</div> */}
      <iframe src={iframeUrl} ref={useragentIframe} onLoad={iframeLoad} className={styles.iframe} />
      <div className={styles.back} onClick={() => (window.location.href = '/learning')}>
        <i className={styles.icon} />
        返回学习中心
      </div>
      {downurl ? (
        <div className={classNames(styles.player, styles.playerNoVideo)}>
          <a href={downurl} target="_blank" rel="noreferrer">
            下载专用播放器
          </a>
        </div>
      ) : videoSrc ? (
        <iframe className={styles.video} src={videoSrc} frameBorder="0" allowfullscreen="true" />
      ) : (
        <div className={styles.player} id="zhy-cjjoy-video-player" />
      )}
      <div className={styles.footer}>
        <div className={styles.teacher}>
          <i
            className={styles.avatar}
            style={{ backgroundImage: `url(${classDetail.avatar})` }}
            onClick={() => goTeacherDetail(classDetail?.uid)}
          />
          <div className={styles.name} onClick={() => goTeacherDetail(classDetail?.uid)}>
            {classDetail.username} 老师
          </div>
          {/* {classDetail.teacherqq && (
            <div className={styles.tag}>老师QQ：{classDetail.teacherqq || '-'}</div>
          )}
          {classDetail.weixinteacher && (
            <div className={styles.tag}>老师微信：{classDetail.weixinteacher || '-'}</div>
          )} */}
        </div>
        {classDetail?.studentnum && (
          <div className={styles.mynum}>
            我的学号： <span className={styles.text}>{classDetail.studentnum}</span>
          </div>
        )}
      </div>
    </div>
  );
};

const Menu = ({ playerRef, classId, data, isPay, classDetail, attachs = {} as any }) => {
  const history = useHistory();
  const paramsVid = (history.location as any)?.query?.vid;
  useEffect(() => {
    if (paramsVid) {
    }
  }, [paramsVid]);
  const [height, setHeight] = useState(0);
  useEffect(() => {
    setHeight(document.querySelector('#leftVideoWrapper')?.clientHeight ?? 0);
  }, []);

  const [collapsed, setCollapsed] = useState(false);
  const [materialModalShow, setMaterialModalShow] = useState(false);

  const downoadFile = async () => {
    setMaterialModalShow(true);
  };

  // 是否有素材下载
  const hasDownfile =
    (Array.isArray(attachs.attach) && attachs.attach.length > 0) ||
    (Array.isArray(attachs.disk) && attachs.disk.length > 0);
  return (
    <>
      {materialModalShow && (
        <MaterialModal attachs={attachs} onClose={() => setMaterialModalShow(false)} />
      )}
      <div
        className={classNames(styles.menuWrapper, { [styles.collapsed]: collapsed })}
        style={{ height }}
        id="zhy-menu"
      >
        <div className={styles.mulu}>
          目录
          {hasDownfile && <DownLoadMaterial onClick={downoadFile} />}
        </div>
        <div className={styles.menu}>
          <Catalogue classId={classId} data={data} isPay={isPay} playerRef={playerRef} />
        </div>
      </div>
      <div
        className={classNames(styles.sl, { [styles.collapsed]: collapsed })}
        onClick={() => setCollapsed(!collapsed)}
      >
        <i className={styles.icon} />
      </div>
    </>
  );
};

const Index = (props) => {
  const history = useHistory();
  const [loading, setLoading] = useState(true);
  const classId = props.match.params.classId;
  const [menu, setMenu] = useState<any>([]);
  const [classDetail, setClassDetail] = useState<any>({});
  const [attachs, setAttachs] = useState({});
  const [isPay, setPayed] = useState(true);
  const lid = (history.location as any)?.query?.lid;
  const top = (history.location as any)?.query?.top;
  const transformData = (data = [] as any[]) => {
    const hasC = data.some((item) => item.cid != 0 && item.children && item.children.length > 0);
    const newData: any[] = [...data];
    const mf: any = {
      header: '试听课',
      children: [],
    };
    const dlc: any = {
      header: '追加课（DLC课时）',
      children: [],
    };
    newData.forEach((item: any, index) => {
      newData[index] = {
        ...item,
        header: item.name,
      };
      const children = item.children;
      if (children && Array.isArray(children)) {
        children.forEach((item, index) => {
          const newItem = {
            ...item,
            title: item.name,
          };
          children[index] = newItem;
          // if (item.type == -1) {
          //   mf.children.push(newItem)
          //   children[index].delete = true;
          // }
          // if (item.type == 1) {
          //   dlc.children.push(newItem);
          //   children[index].delete = true;
          // }
        });
        newData[index].children = children.filter((item) => item && item.delete !== true);
      }
    });
    const othersIndex = newData.findIndex((item) => item.cid == 0);
    if (othersIndex > -1) {
      newData[othersIndex].header = hasC ? '其他课时' : '课程视频';
      // if (dlc.children.length > 0) {
      //   newData.splice(othersIndex, 0, dlc)
      // }
    }

    if (mf.children.length > 0) {
      newData.unshift(mf);
    }
    // if (dlc.children.length > 0) {
    //   newData.push(dlc);
    // }
    return newData.filter((item) => Array.isArray(item.children) && item.children.length > 0);
  };
  const getData = async () => {
    const response = await allGet({
      params: { mod: 'user', do: 'learn', classid: classId, version: 'pc1.0' },
    });
    const data = transformData(response?.data?.chapters || []);
    setMenu(data);
    setClassDetail(response?.data?.course || {});
    let newLid = lid;
    if (newLid === undefined) {
      newLid = data?.[0]?.children?.[0]?.lid;

      location.href = `/center/video/player/${classId}?lid=${data?.[0]?.children?.[0]?.lid}`;
      // history.replace(`/center/video/player/${classId}?lid=${data?.[0]?.children?.[0]?.lid}`);
      // playerRef.current.changeVid({
      //   vid: newLid
      // });
    }
    playerRef.current.play(newLid);
    setLoading(false);
  };

  const getClassDetail = async () => {
    const detail = await allGet({
      params: { mod: 'course', do: 'detail', classid: classId, version: 'pc1.0' },
    });
    setPayed(!!detail?.data?.payed);
    setAttachs(detail?.data?.attachs);
  };
  useEffect(() => {
    getData();
    getClassDetail();
    return () => {
      clearTimeout(videoplayCheckStartTimer);
    };
  }, []);

  useEffect(() => {
    const dom = document.getElementById('zhy-menu');
    if (menu?.length > 0 && dom && top) {
      dom.scrollTop = top;
    }
  }, [menu]);

  useEffect(() => {
    // setMenu([
    //   {
    //     header: '试听课',
    //     items: [{ type: 1, title: 'Blender能做什么？', vid: '88083abbf5bcf1356e05d39666be527a_8', }]
    //   },
    //   {
    //     header: '第一章 对软件的整体认识和界面的讲解',
    //     items: [{ type: 2, title: 'Blender能做什么？', vid: '88083abbf5bcf1356e05d39666be527a_7', workStatus: 1, workReward: '完成作业奖励：50点CG券' }, { type: 2, title: '进阶案例：机械设计建模', vid: 3 }, { type: 2, title: '吉祥物建模', vid: 8888 }, { type: 2, title: 'Blender能做什么2？', vid: 4 },]
    //   },
    //   {
    //     header: '第二章 对软件的整体认识和界面的讲解',
    //     items: [{ type: 2, title: 'Blender能做什么2？', vid: 22, workStatus: 2, }, { type: 2, title: '进阶案例：机械设计建模22', vid: 33 }, { type: 2, title: '吉祥物建模22', vid: 55 }, { type: 2, title: 'Blender能做什么22？', vid: 44 },]
    //   },
    //   {
    //     header: '追加课（DLC课时）',
    //     items: [{ type: 3, title: '进阶案例：场景的设计与建模', vid: 5, lock: true, lockType: 1 }, { type: 3, title: '进阶案例：吉祥物IP的建模与商业计划书', vid: 6, lock: true, lockType: 2 }, { type: 3, title: '进阶案例：机械设计建模', vid: 7, lock: true, lockType: 3 }, { type: 3, title: '进阶案例：机械设计建模2', vid: 8, workStatus: 1, workReward: '完成作业奖励：50点CG券' }]
    //   },
    // ])
    // // 没有vid 就默然选第一个id
    // if (vid === undefined) {
    //   history.replace(`/center/video/player/${classId}?vid=${1}`)
    // }
    setLoading(false);
  }, []);
  const playerRef = useRef<any>(null);
  // console.log(ABC.AES, 'ABCABCABC');
  return (
    <div className={styles.page}>
      {!loading && (
        <>
          <Left playerRef={playerRef} isPay={isPay} classDetail={classDetail} />
          <Menu
            playerRef={playerRef}
            classId={classId}
            data={menu}
            isPay={isPay}
            classDetail={classDetail}
            attachs={attachs}
          />
        </>
      )}
    </div>
  );
};

export default Index;
